package com.eric.springboot.controller;

import com.eric.springboot.common.CommonResult;
import com.eric.springboot.utils.JwtTokenUtil;
import com.eric.springboot.utils.SecurityUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Eric
 * @date 2021.1.26
 */
@RestController
@RequestMapping("/test")
@Api(tags = "测试")
@Slf4j
public class TestController {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @GetMapping("/getTokenInfo")
    @ApiOperation("获取token信息")
    @PreAuthorize("hasAnyAuthority('admin')")
    public CommonResult getTokenInfo(HttpServletRequest request){
        log.info("获取token信息");
        String authorization = request.getHeader("Authorization");
        String token = authorization.substring(7);
        Claims claims = Jwts.parser()
                .setSigningKey("springboot")
                .parseClaimsJws(token)
                .getBody();
        Map<String,Object> map = new HashMap<>();
        map.put("userName", SecurityUtils.getCurrentUserName());
        map.put("created",new Date(Long.parseLong(claims.get("created").toString())));
        map.put("roles",claims.get("roles"));
        map.put("expiration",claims.getExpiration());
        map.put("userId",SecurityUtils.getCurrentUserId());
        return CommonResult.success(map);
    }

    @GetMapping("/refreshToken")
    public CommonResult refreshToken(String token){
        Map<String,Object> map = new HashMap<>();
        map.put("token",jwtTokenUtil.refreshHeadToken(token));
        return CommonResult.success(map);
    }

    @GetMapping("/exception")
    @ApiOperation("测试异常")
    @PreAuthorize("hasAnyAuthority('user')")
    public CommonResult exception(){
        System.out.println(1/0);
        return CommonResult.success(null);
    }
}
